<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :on-change="handleChange"
      :auto-upload="false"
      style="width: 200px; margin-bottom: 10px"
    >
      <el-button type="primary">导入未完成发货单</el-button>
    </el-upload>
    <el-button
      type="primary"
      v-if="tableData && tableData.length > 0"
      :disabled="selectData.length < 1"
      @click="toPrintMany"
      >批量打印</el-button
    >
    <el-button
      type="primary"
      v-if="tableData && tableData.length > 0"
      :disabled="selectData.length < 1"
      @click="toExportFile"
      >导出选中文件</el-button
    >
    <el-button
      type="primary"
      v-if="orginData && orginData.length > 0"
      @click="toExportAllFile"
      >导出全部文件</el-button
    >
    <div
      style="width: 100%; margin-top: 30px"
      v-if="tableData && tableData.length > 0"
    >
      <el-table
        border
        show-summary
        :summary-method="getSummaries"
        :data="tableData"
        @selection-change="handleSelectionChange"
        height="650"
      >
        <el-table-column type="selection" width="55" label="序号" />
        <el-table-column prop="购买方名称" label="购买方名称" />
        <el-table-column prop="货物或应税劳务名称" label="货物或应税劳务名称" />
        <el-table-column prop="单位" label="单位" />
        <el-table-column prop="单价" label="单价" />
        <el-table-column prop="orderNum" label="数量" />
        <el-table-column prop="jine" label="金额"> </el-table-column>
        <!-- <el-table-column prop="数量"
                       label="数量" /> -->
        <!-- <el-table-column prop="价税合计"
                       label="价税合计" /> -->
        <el-table-column prop="plateNumber" label="车牌号" />
        <el-table-column prop="name" label="司机" />
        <el-table-column prop="phone" label="手机号" />

        <el-table-column prop="time" label="发货日期" />
        <el-table-column>
          <template #default="scope">
            <el-button @click="printOrder(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page="currentPage"
      :total="orginData.length"
      :page-sizes="[10, 20, 50, 100]"
      v-if="tableData && tableData.length > 0"
      layout="total, prev,pager, next, jumper,sizes"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <InvoiceDialog ref="printOrederRef"></InvoiceDialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import * as XLSX from "xlsx";
import InvoiceDialog from "../excelTest/components/InvoiceDialog.vue";

let fileTemp = ref(null);
let orginData = ref([]);
let indexList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

//数据分页
let currentPage = ref(1);
let pageSize = ref(10);
let tableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return orginData.value.slice(startIndex, endIndex);
});

const handlePageChange = (newPage: number) => {
  currentPage.value = newPage;
};
const handleSizeChange = (val: number) => {
  pageSize.value=val
}
/**
 * 改变文件
 */
const handleChange = (file: any, fileList: any) => {
  fileTemp.value = file.raw;
  if (fileTemp.value) {
    if (
      fileTemp.value.type ==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      fileTemp.value.type == "application/vnd.ms-excel"
    ) {
      importfxx(fileTemp.value);
    } else {
      ElMessage.warning({
        type: "warning",
        message: "附件格式错误，请删除后重新上传！",
      });
    }
  } else {
    ElMessage.warning({
      type: "warning",
      message: "请上传附件！",
    });
  }
};

/**
 * 导入文件
 */
const importfxx = (val: any) => {
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    orginData.value = getDataByIndexArray(jsonData, indexList);
    console.log(orginData.value);
  };
  reader.readAsArrayBuffer(val);
};

/**
 * 整理的数据
 * @param data
 * @param indexArray
 */
function getDataByIndexArray(data, indexArray) {
  const result = [];

  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const rowData = {};

    for (let j = 0; j < indexArray.length; j++) {
      const index = indexArray[j];
      rowData[data[0][index]] = row[index];
    }

    result.push(rowData);
  }

  return result;
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (
      !values.every((value) => Number.isNaN(value)) &&
      (index === 4 || index === 5)
    ) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "N/A";
    }
  });

  return sums;
};
let printOrederRef = ref();
/**
 * 打印预览发货单
 */
const printOrder = (val: any) => {
  printOrederRef.value.init([val]);
};
// 批量打印
const toPrintMany = () => {
  printOrederRef.value.init([...selectData.value]);
};
//选中的数据
let selectData: any = ref([]);
/**
 * 选择多个
 * @param val
 */
const handleSelectionChange = (val: any) => {
  console.log("多个数据：", val);
  selectData.value = val;
};

const router = useRouter();
/**
 * 跳转详情
 */
const toDetail = () => {
  console.log(JSON.stringify(selectData.value));

  router.push({
    path: "/ExcelDetail",
    query: { selectData: JSON.stringify(selectData.value) },
  });
};

/**************** 导入未完成的发货单 *****************/

/**
 * 导出数据
 */
const toExportFile = () => {
  if (selectData.value.length <= 0) {
    ElMessage.warning("请选择数据！");
    return false;
  }
  let tableData = [
    [
      "序号",
      "购买方名称",
      "货物或应税劳务名称",
      "单位",
      "单价",
      "orderNum",
      "jine",
      "plateNumber",
      "name",
      "phone",
      "time",
    ], //导出表头
  ]; // 表格表头
  selectData.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      index + 1,
      item.购买方名称,
      item.货物或应税劳务名称,
      item.单位,
      item.单价,
      item.orderNum,
      item.jine,
      item.plateNumber,
      item.name,
      item.phone,
      item.time,
    ];
    tableData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "发货单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
const toExportAllFile = () => {
  if (orginData.value.length <= 0) {
    ElMessage.warning("请选择数据！");
    return false;
  }
  let tableData = [
    [
      "序号",
      "购买方名称",
      "货物或应税劳务名称",
      "单位",
      "单价",
      "orderNum",
      "jine",
      "plateNumber",
      "name",
      "phone",
      "time",
    ], //导出表头
  ]; // 表格表头
  orginData.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      index + 1,
      item.购买方名称,
      item.货物或应税劳务名称,
      item.单位,
      item.单价,
      item.orderNum,
      item.jine,
      item.plateNumber,
      item.name,
      item.phone,
      item.time,
    ];
    tableData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "发货单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
</script>

<style scoped>
.item {
  width: 800px;
  height: 50px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
</style>
